import apiConfig from "./apiConfig.js";

let cachedActionTypes = [];
let cachedSelectors = [];

// 获取操作类型列表
async function fetchActionTypes() {
  try {
    const response = await fetch(apiConfig.getURL("action_types", "list"));
    if (!response.ok) throw new Error("获取操作类型列表失败");
    return (await response.json()) || [];
  } catch (error) {
    console.error("获取操作类型失败:", error);
    throw error;
  }
}

// 获取元素选择器列表
async function fetchElementSelectors() {
  try {
    const response = await fetch(apiConfig.getURL("selectors", "list"));
    if (!response.ok) throw new Error("获取元素选择器列表失败");
    return (await response.json()) || [];
  } catch (error) {
    console.error("获取元素选择器失败:", error);
    throw error;
  }
}

// 按模块ID获取元素列表
async function fetchElementsByModuleId(moduleId) {
  try {
    if (!moduleId) throw new Error("模块ID不能为空");
    const response = await fetch(
      apiConfig.getURL("modules_id", "list") + "&moduleId=" + moduleId
    );
    const result = await response.json();
    if (!response.ok) throw new Error("获取模块元素列表失败");
    return result;
  } catch (error) {
    console.error(`获取模块(ID: ${moduleId})元素失败:`, error);
    throw error;
  }
}

// 初始化元素管理功能
async function initElementManagement() {
  try {
    // 获取模块列表用于选择
    const modulesResponse = await fetch(apiConfig.getURL("modules", "list"));
    if (!modulesResponse.ok) throw new Error("获取模块列表失败");
    const modules = (await modulesResponse.json()) || [];

    // 填充模块选择框（保留默认选项）
    const moduleSelect = document.getElementById("module");
    if (!moduleSelect) throw new Error("未找到模块选择框");

    // 保留第一个默认选项
    const defaultOption = moduleSelect.options[0];
    moduleSelect.innerHTML = "";
    moduleSelect.appendChild(defaultOption);

    // 添加模块列表
    modules.forEach((m) => {
      const option = document.createElement("option");
      option.value = m.modulesId;
      option.textContent = m.modulesName;
      moduleSelect.appendChild(option);
    });

    // 获取操作类型列表并填充（保留默认选项）
    cachedActionTypes = await fetchActionTypes(); // 缓存操作类型列表
    const actionTypeSelect = document.getElementById("actionType");
    if (actionTypeSelect) {
      // 保留第一个默认选项
      const defaultActionOption = actionTypeSelect.options[0];
      actionTypeSelect.innerHTML = "";
      actionTypeSelect.appendChild(defaultActionOption);

      // 添加操作类型列表
      cachedActionTypes.forEach((type) => {
        const option = document.createElement("option");
        option.value = type.id;
        option.textContent = type.name;
        actionTypeSelect.appendChild(option);
      });
    }

    // 获取元素选择器列表并填充（保留默认选项）
    cachedSelectors = await fetchElementSelectors();
    const selectorSelect = document.getElementById("elementSelector");
    if (selectorSelect) {
      // 保留第一个默认选项
      const defaultSelectorOption = selectorSelect.options[0];
      selectorSelect.innerHTML = "";
      selectorSelect.appendChild(defaultSelectorOption);

      // 添加选择器列表
      cachedSelectors.forEach((selector) => {
        const option = document.createElement("option");
        option.value = selector.id;
        option.textContent = selector.name;
        selectorSelect.appendChild(option);
      });
    }

    // 清空元素列表，等待用户选择模块
    const elementList = document.getElementById("elementList");
    if (elementList) {
      // 获取提示元素
      const selectModuleTip = document.getElementById("selectModuleTip");
      const noElementsTip = document.getElementById("noElementsTip");

      // 移除现有的元素项
      const currentElements = elementList.querySelectorAll(
        ".element-item:not(#elementItemTemplate)"
      );
      currentElements.forEach((item) => item.remove());

      // 显示选择模块提示
      selectModuleTip.style.display = "";
      noElementsTip.style.display = "none";
    }
  } catch (error) {
    console.error("初始化模块表单失败:", error);
    alert("初始化错误: " + error.message);
  }
}

// 元素管理页面初始化
document.addEventListener("DOMContentLoaded", async () => {
  const form = document.getElementById("addElementForm");
  if (!form) return; // 非元素管理页面不执行

  try {
    // 初始化元素管理功能
    await initElementManagement();

    // 监听模块选择变化，加载相关元素
    const moduleSelect = document.getElementById("module");
    if (moduleSelect) {
      moduleSelect.addEventListener("change", async (e) => {
        try {
          const moduleId = parseInt(e.target.value);
          if (moduleId) {
            // 按模块ID加载元素列表
            const result = await fetchElementsByModuleId(moduleId);
            updateElementList(result, moduleId);
          } else {
            updateElementList({ code: 500 }, null);
          }
        } catch (error) {
          console.error("加载模块元素失败:", error);
        }
      });
    }

    // 绑定表单提交事件
    form.addEventListener("submit", async (e) => {
      e.preventDefault();

      const formData = {
        moduleId: parseInt(e.target.elements.module.value),
        elementContent: e.target.elements.elementContent.value.trim(),
        actionType: e.target.elements.actionType.value,
        elementSelector: e.target.elements.elementSelector.value,
        textValue: e.target.elements.textValue.value.trim(),
        description: e.target.elements.description.value.trim(),
        elementId: e.target.elements.elementId
          ? e.target.elements.elementId.value
          : null,
      };

      if (!formData.textValue) {
        alert("请输入文本值");
        return;
      }

      if (!formData.elementContent) {
        alert("请输入操作项");
        return;
      }

      try {
        const isEditMode =
          form.querySelector('[name="editMode"]')?.value === "true";
        const elementId = isEditMode
          ? form.querySelector('[name="elementId"]')?.value
          : null;

        // 根据编辑模式确定URL和方法
        const url = isEditMode
          ? apiConfig.getURL("elements", "update").replace("{id}", elementId)
          : apiConfig.getURL("elements", "create");

        const method = isEditMode ? "PUT" : "POST";

        const response = await fetch(url, {
          method: method,
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(formData),
        });

        const responseData = await response.json();
        if (responseData.code !== 200) {
          throw new Error(
            responseData.msg || (isEditMode ? "元素更新失败" : "元素创建失败")
          );
        }

        alert(isEditMode ? "元素更新成功！" : "元素添加成功！");
        e.target.reset();

        // 重置编辑状态
        if (isEditMode) {
          const editModeInput = form.querySelector('[name="editMode"]');
          if (editModeInput) editModeInput.remove();

          const elementIdInput = form.querySelector('[name="elementId"]');
          if (elementIdInput) elementIdInput.remove();
        }

        await refreshElementList();
      } catch (error) {
        console.error("提交失败:", error);
        alert(`操作失败: ${error.message}`);
      }
    });
  } catch (error) {
    console.error("页面初始化失败:", error);
    alert(`初始化错误: ${error.message}`);
  }
});

// 更新指定模块的元素列表
function updateElementList(response, moduleId) {
  try {
    const elementList = document.getElementById("elementList");
    if (!elementList) throw new Error("未找到元素列表容器");
    // 添加左侧容器样式
    elementList.style.maxHeight = "70vh"; // 设置最大高度
    elementList.style.overflowY = "auto"; // 添加垂直滚动条
    elementList.style.padding = "5px"; // 减少内边距
    elementList.style.border = "1px solid #ddd"; // 添加边框
    elementList.style.borderRadius = "4px"; // 圆角边框
    elementList.style.backgroundColor = "white"; // 背景色

    // 获取提示元素
    const selectModuleTip = document.getElementById("selectModuleTip");
    const noElementsTip = document.getElementById("noElementsTip");
    const elementTemplate = document.getElementById("elementItemTemplate");

    // 移除所有现有的元素项（除了模板和提示外）
    const currentElements = elementList.querySelectorAll(
      ".element-item:not(#elementItemTemplate)"
    );
    currentElements.forEach((item) => item.remove());

    // 根据响应码设置提示
    if (response.code === 200) {
      if (response.msg && response.msg.length > 0) {
        noElementsTip.style.display = "none";
        selectModuleTip.style.display = "none";
        // 遍历并添加元素
        response.msg.forEach((element) => {
          const item = elementTemplate.cloneNode(true);
          item.removeAttribute("id");
          item.style.display = "";

          // 填充元素数据
          item.querySelector(".action-content-value").textContent =
            element.elementContent || "未知";
          // 使用缓存的操作类型列表
          const actionType = cachedActionTypes.find(
            (type) => type.id === element.actionType
          );
          item.querySelector(".action-type-value").textContent = actionType
            ? actionType.name
            : "未知";
          // 使用缓存的选择器列表
          const selector = cachedSelectors.find(
            (sel) => sel.id === element.elementSelector
          );
          item.querySelector(".selector-value").textContent = selector
            ? selector.name
            : "未知";

          // 处理文本值显示
          if (element.textValue) {
            const textValueEl = item.querySelector(".text-value");
            textValueEl.style.display = "";
            textValueEl.querySelector(".text-content").textContent =
              element.textValue;
          }

          // 绑定删除事件
          item.querySelector(".delete-button").addEventListener("click", () => {
            deleteElement(element.moduleId, element.elementId);
          });
          //绑定编辑事件
          item.querySelector(".edit-button").addEventListener("click", (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            fillFormForEditing(element);
          });

          // 添加到列表
          elementList.appendChild(item);
        });
      } else {
        noElementsTip.textContent = "暂无元素数据";
        noElementsTip.style.display = "";
        selectModuleTip.style.display = "none";
      }
    } else if (response.code === 404) {
      noElementsTip.textContent = "暂无元素数据";
      noElementsTip.style.display = "";
      selectModuleTip.style.display = "none";
    } else {
      noElementsTip.style.display = "none";
      selectModuleTip.style.display = "";
    }
  } catch (error) {
    console.error("更新元素列表失败:", error);
    alert(`操作失败: ${error.message}`);
  }
}

// 刷新元素列表 (用于添加/删除元素后更新)
async function refreshElementList() {
  try {
    // 检查当前选中的模块
    const moduleSelect = document.getElementById("module");
    if (!moduleSelect) throw new Error("未找到模块选择框");

    const moduleId = parseInt(moduleSelect.value);
    if (!moduleId) {
      // 如果没有选中模块，显示提示信息
      const elementList = document.getElementById("elementList");
      if (elementList) {
        // 获取提示元素
        const selectModuleTip = document.getElementById("selectModuleTip");
        const noElementsTip = document.getElementById("noElementsTip");

        // 移除现有的元素项
        const currentElements = elementList.querySelectorAll(
          ".element-item:not(#elementItemTemplate)"
        );
        currentElements.forEach((item) => item.remove());

        // 显示选择模块提示
        selectModuleTip.style.display = "";
        noElementsTip.style.display = "none";
      }
      return;
    }

    // 获取当前模块的元素
    const result = await fetchElementsByModuleId(moduleId);
    updateElementList(result, moduleId);
  } catch (error) {
    console.error("刷新列表失败:", error);
    alert(`操作失败: ${error.message}`);
  }
}

// 删除元素
async function deleteElement(moduleId, elementId) {
  if (!confirm("确定要删除此元素吗？")) return;

  try {
    // 构造正确的URL，确保包含moduleId和elementId
    const url = `${apiConfig.getURL(
      "elements",
      "delete"
    )}?moduleId=${moduleId}&elementId=${elementId}`;

    const response = await fetch(url, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
      },
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || "删除元素失败");
    }

    alert("元素删除成功！");
    await refreshElementList();
  } catch (error) {
    console.error("删除失败:", error.message);
    alert(`操作失败: ${error.message}`);
  }
}

// 新增填充表单函数
function fillFormForEditing(element) {
  console.log("准备编辑元素:", element);
  console.log("yuansu", element.elementId);
  const form = document.getElementById("addElementForm");
  form.elements.module.value = element.moduleId;
  form.elements.elementContent.value = element.elementContent || "";
  form.elements.actionType.value = element.actionType || "";
  form.elements.elementSelector.value = element.elementSelector || "";
  form.elements.textValue.value = element.textValue || "";
  form.elements.description.value = element.description || "";
  if (element.elementId) {
    const elementIdInput = document.createElement("input");
    console.log("yuansu2", elementIdInput);
    elementIdInput.type = "hidden";
    elementIdInput.name = "elementId";
    elementIdInput.value = element.elementId;
    form.appendChild(elementIdInput);
    console.log("yuansu3", form);
  }

  // 添加隐藏字段存储编辑状态
  if (!form.querySelector('[name="editMode"]')) {
    const input = document.createElement("input");
    input.type = "hidden";
    input.name = "editMode";
    input.value = "true";
    form.appendChild(input);
  }

  // 滚动到表单顶部
  document
    .querySelector(".main-content")
    .scrollIntoView({ behavior: "smooth" });
}

// 导出公共函数，供页面使用
window.deleteElement = deleteElement;
